package com.andy.blog.quartz.service.impl;

import com.andy.blog.common.constant.BaseConstants;
import com.andy.blog.common.constant.ScheduleConstants;
import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.exception.job.TaskException;
import com.andy.blog.common.page.PageUtilsDTO;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.SysJobDO;
import com.andy.blog.dal.service.SysJobDalService;
import com.andy.blog.dal.vo.SysJobVO;
import com.andy.blog.quartz.dto.SysJob;
import com.andy.blog.quartz.dto.SysJobDTO;
import com.andy.blog.quartz.service.SysJobBusService;
import com.andy.blog.quartz.util.CronUtils;
import com.andy.blog.quartz.util.ScheduleUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务调度信息 服务层
 * Created by andy on 2023-04-05 11:38
 */
@Service
public class SysJobBusServiceImpl implements SysJobBusService {
    @Autowired
    private Scheduler scheduler;

    @Resource
    private SysJobDalService sysJobDalService;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJobDO> jobList = sysJobDalService.selectListByCondition(null);
        List<SysJobVO> sysJobVOS = TransformUtils.transformList(jobList, SysJobVO.class);
        for (SysJobVO job : sysJobVOS) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     *
     * @param sysJobVO 调度信息
     */
    @Override
    public PageUtilsDTO<SysJobDTO> selectListByPage(SysJobVO sysJobVO) {
        IPage<SysJobDO> sysJobDOIPage = sysJobDalService.selectByList(sysJobVO);

        return PageUtilsDTO.build(sysJobDOIPage.getTotal(), TransformUtils.transformList(sysJobDOIPage.getRecords(), SysJobDTO.class));
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJobDTO selectById(Long jobId) {
        SysJobDO sysJobDO = sysJobDalService.selectById(jobId);
        return TransformUtils.transform(sysJobDO, SysJobDTO.class);
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pauseJob(SysJobVO job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        sysJobDalService.updateJob(job);
        scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    /**
     * 恢复任务
     *
     * @param sysJobVO 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resumeJob(SysJobVO sysJobVO) throws SchedulerException {
        Long jobId = sysJobVO.getId();
        String jobGroup = sysJobVO.getJobGroup();
        sysJobVO.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        sysJobDalService.updateJob(sysJobVO);
        scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));

    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = sysJobDalService.deleteJobById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SysJobDO sysJobDO = sysJobDalService.selectById(jobId);
            SysJob sysJob = new SysJob();
            sysJob.setJobId(jobId );
            sysJob.setJobGroup(sysJobDO.getJobGroup());
            deleteJob(sysJob);
        }
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(SysJobVO job) throws SchedulerException {
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            pauseJob(job);
        }
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJobVO job) throws SchedulerException {
        boolean result = false;
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        SysJobDTO dos = selectById(job.getId());
        SysJob properties = TransformUtils.transform(dos, SysJob.class);
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertJob(SysJobVO job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            throw new BlogServiceException("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), BaseConstants.LOOKUP_RMI)) {
            throw new BlogServiceException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{BaseConstants.LOOKUP_LDAP, BaseConstants.LOOKUP_LDAPS})) {
            throw new BlogServiceException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{BaseConstants.HTTP, BaseConstants.HTTPS})) {
            throw new BlogServiceException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), BaseConstants.JOB_ERROR_STR)) {
            throw new BlogServiceException("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            throw new BlogServiceException("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }

        sysJobDalService.insertSelective(job);

        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateJob(SysJobVO job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            throw new BlogServiceException("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), BaseConstants.LOOKUP_RMI)) {
            throw new BlogServiceException("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{BaseConstants.LOOKUP_LDAP, BaseConstants.LOOKUP_LDAPS})) {
            throw new BlogServiceException("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{BaseConstants.HTTP, BaseConstants.HTTPS})) {
            throw new BlogServiceException("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), BaseConstants.JOB_ERROR_STR)) {
            throw new BlogServiceException("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            throw new BlogServiceException("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        SysJobDTO dos = selectById(job.getId());
        SysJob properties = TransformUtils.transform(dos, SysJob.class);
        sysJobDalService.updateJob(job);

        updateSchedulerJob(job, properties.getJobGroup());
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJobVO job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }

    @Override
    public List<SysJobDTO> selectListByCondition(SysJobVO sysJobVO) {
        List<SysJobDO> sysJobDOS = sysJobDalService.selectListByCondition(sysJobVO);
        return TransformUtils.transformList(sysJobDOS, SysJobDTO.class);
    }
}
